package springboot_rabbitmq.producer;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

@RestController
@RequestMapping("/ttl")
@Slf4j
public class SendMsgController {
    @Autowired
    private RabbitTemplate rabbitTemplate;


    /*
    *  队列ttl
    * */
    @GetMapping("sendMsg/{message}")
    public void sendMsg(@PathVariable String message){
        // 直接用日志
        log.info("当前时间:{}发送一条消息{}给两个队列",new Date(),message);
        /*
        * 发送给那个交换机
        * 发送路由key
        * 发送信息
        * */
        rabbitTemplate.convertAndSend("X","XA","消息来自TTL为10S队列QA"+message);
        rabbitTemplate.convertAndSend("X","XB","消息来自TTL为40S队列QB"+message);
    }


    /*
    * 消息ttl
    * */
    @GetMapping("sendTtlMsg/{message}/{ttlTime}")
    public void sendTtlMsg(@PathVariable String message,@PathVariable String ttlTime){
        log.info("当前时间:{}发送一条时长:{}消息:{}给队列QC",new Date(),ttlTime,message);
        //消息TTL的设置
        MessagePostProcessor messagePostProcessor=correlationData->{
            correlationData.getMessageProperties().setExpiration(ttlTime);
            return correlationData;
        };
        rabbitTemplate.convertAndSend("X","XC",message,messagePostProcessor);
    }





    /*
    *  插件延时发送
    * */
    public static final String DELAYED_QUEUE_NAME = "delayed.queue";
    public static final String DELAYED_EXCHANGE_NAME = "delayed.exchange";
    public static final String DELAYED_ROUTING_KEY = "delayed.routingKey";

    @GetMapping("sendDelayMsg/{message}/{delayTime}")
    public void sendDelayMsg(@PathVariable String message,@PathVariable String delayTime){
        log.info("当前时间:{}发送一条时长:{}延迟消息:{}给队列delayed.queue",new Date(),delayTime,message);
        //消息delay时间的设置
        MessagePostProcessor messagePostProcessor=correlationData->{
            correlationData.getMessageProperties().setDelay(Integer.valueOf(delayTime));
            return correlationData;
        };
        rabbitTemplate.convertAndSend(DELAYED_EXCHANGE_NAME,DELAYED_ROUTING_KEY,message,messagePostProcessor);
    }



}
